package dsk.demo.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import dsk.demo.common.utils.PageQuery;
import dsk.demo.common.utils.R;
import dsk.demo.product.dao.UserDao;
import dsk.demo.product.entity.UserEntity;
import dsk.demo.product.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserDao userDao;

    @Override
    public IPage getList(UserEntity ivo, PageQuery pageQuery) {
        IPage<UserEntity> userEntityIPage = userDao.selectPage(pageQuery.build(), Wrappers.<UserEntity>lambdaQuery()
                .like(StrUtil.isNotBlank(ivo.getUsername()), UserEntity::getUsername, ivo.getUsername())
                .like(StrUtil.isNotBlank(ivo.getEmail()), UserEntity::getEmail, ivo.getEmail())
                .like(StrUtil.isNotBlank(ivo.getMobile()), UserEntity::getMobile, ivo.getMobile())
                .eq(ivo.getId() != null, UserEntity::getId, ivo.getId())
        );
        return userEntityIPage;
    }

    @Override
    public Integer saveUser(UserEntity ivo) {
        return userDao.insert(ivo);
    }

    /**
     * 登录
     *
     * @param ivo
     */
    @Override
    public R login(UserEntity ivo) {
        // 查询密码,
        UserEntity userEntity = userDao.selectOne(Wrappers.<UserEntity>lambdaQuery()
                .and(w -> {
                    w.eq(UserEntity::getEmail, ivo.getUsername())
                            .or().eq(UserEntity::getUsername, ivo.getUsername());
                })
        );
        if (userEntity == null) {
            return R.error(90002, "用户名不存在");
        }
        if (userEntity.getPassword().equals(ivo.getPassword())) {
            // 更新当前登录状态 和 登录凭证, 登录凭证存在cookie中
            // 部分请求必须携带改凭证才可访问
            userEntity.setLoginTime(new Date());
            String token = UUID.randomUUID().toString();
            userEntity.setToken(token);
            userDao.updateById(userEntity);
            return R.ok("登录成功", token);
        }
        return R.error(90002, "用户名或密码错误");
    }
}
